//
//  YCHomeVC.swift
//  YCWeiBoSwift
//
//  Created by 刘胤辰 on 16/7/19.
//  Copyright © 2016年 it.com. All rights reserved.
//

import UIKit

class YCHomeVC: YCVistorVC {

    lazy var listStatusViewModel:YCHomeViewModel = YCHomeViewModel()
    
    // MARK: -- 懒加载
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.registerClass(YCHomeCell.self, forCellReuseIdentifier: "HomeCellID")
        tableView.estimatedRowHeight=200

        //加载数据
        loadData()
        
        setUI()
    }
}

extension YCHomeVC {
    
    
     override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return listStatusViewModel.statusLists.count
    }
     override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell=tableView.dequeueReusableCellWithIdentifier("HomeCellID", forIndexPath: indexPath) as! YCHomeCell
        let model = listStatusViewModel.statusLists[indexPath.row]
        
        cell.status = model
        
        return cell
        
    }
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        
        if indexPath.item == listStatusViewModel.statusLists.count - 1 {
            pullView.startAnimating()
            loadData()
        }
    }
    
    override func setUI(){
        //添加刷新视图
        setRefreshControll()
        
        pullView.color=UIColor.redColor()
    }
    
    override func setRefreshControll(){
        
        //添加刷新视图
        tableView.addSubview(refresh)
        
        //设置refresh的监听方法
        refresh.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        
        tableView.tableFooterView=pullView
    }
    
    //加载数据
    func loadData(){
        //加载数据之前返回这两个数据
        //判断是上拉刷新
        var since_id:Int64=0
        var max_id:Int64=0
        
        if pullView.isAnimating() {
            
            max_id=listStatusViewModel.statusLists.last?.id ?? 0
            
            if max_id > 0{
                max_id-=1
            }
        }else{
            
            since_id=listStatusViewModel.statusLists.first?.id ?? 0
        }
        listStatusViewModel.loadWebHomeData(pullView.isAnimating(), since_id: since_id, max_id: max_id) { (isSuccess) -> () in
            if isSuccess {
                
                self.tableView.reloadData()
                self.refresh.endRefreshing()
                self.pullView.stopAnimating()
            }else{
                print("请求失败")
            }
        }
    }
}

